package org.example.servicecounselor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.model.manage.bean.po.CounselorMajor;
import org.example.model.manage.bean.po.Major;
import org.example.model.manage.bean.po.Student;
import org.example.model.manage.bean.po.security.User;
import org.example.model.manage.bean.vo.MajorCount;
import org.example.servicecounselor.mapper.CounselorMajorMapper;
import org.example.servicecounselor.mapper.MajorMapper;
import org.example.servicecounselor.mapper.StudentMapper;
import org.example.model.manage.bean.po.security.MyUserDetails;
import org.example.servicecounselor.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  学生服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-16
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private CounselorMajorMapper counselorMajorMapper;

    @Override
    public List<Student> getAllByMajorId(Integer majorId) {
        return studentMapper.selectList(new QueryWrapper<Student>().eq("major_id", majorId));
    }

    @Override
    public List<MajorCount> countByMajor() {
        User user = ((MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser();
        List<CounselorMajor> list = counselorMajorMapper.selectList(new QueryWrapper<CounselorMajor>().eq("counselor_id", user.getTypeId()));
        List<Major> majors = majorMapper.selectList(new QueryWrapper<Major>().in("id", list.stream().map(CounselorMajor::getMajorId).toList()));
        List<MajorCount> majorCounts = new ArrayList<>();

        for(Major m : majors) {
            MajorCount majorCount = new MajorCount();
            majorCount.setMajorName(m.getMajor());
            Long reportNum = studentMapper.selectCount(new QueryWrapper<Student>().eq("major_id", m.getId()).eq("report_check", 1));
            Long unReportNum = studentMapper.selectCount(new QueryWrapper<Student>().eq("major_id", m.getId()).eq("report_check", 0));
            majorCount.setReportNum(reportNum.intValue());
            majorCount.setUnReportNum(unReportNum.intValue());
            majorCount.setReportRate(reportNum.doubleValue() / (reportNum.doubleValue() + unReportNum.doubleValue()));
        }

        return majorCounts;
    }
}